#include "Bullet.h"
#include "DestoryBulletMessage.h"
#include "Game.h"
#include "MessageSystem.h"

CBullet::CBullet(void)
{
	m_eType				= OBJ_BULLET;
	m_fCurrentRotation	= 0.0f;
	owner				= nullptr;
}

CBullet::~CBullet(void)
{
	SetOwner(nullptr);
}

void CBullet::Update (float fElapsedTime)
{
	CEntity::Update (fElapsedTime);
	CGame* pGame = CGame::GetInstance();

	RECT rOverlap;
	RECT rSelf = GetRect();
	RECT rScreen = { 0, 0, pGame->GetWidth(), pGame->GetHeight() };

	if( IntersectRect( &rOverlap, &rSelf, &rScreen ) != TRUE )
	{
	CDestoryBulletMessage* pMsg = new CDestoryBulletMessage(this);
	CMessageSystem::GetInstance()->SendMsg( pMsg );
	pMsg = nullptr;
	}
}

void CBullet::Render (void)
{
	CSGD_TextureManager* pTM = CSGD_TextureManager::GetInstance();
	pTM->Draw( GetImageID(), (int)this->GetPosX()- (int)(GetWidth()*0.5f), (int)this->GetPosY()-(int)(GetHeight()*0.5f), 1.0f, 1.0f, nullptr, float(GetWidth()*0.5f), float(GetHeight()*0.5f), m_fCurrentRotation );
}

RECT CBullet::GetRect (void) const
{
	RECT collision = {(int)this->GetPosX()- (int)(GetWidth()*0.5f), (int)this->GetPosY()-int(GetHeight()*0.5f), (int)this->GetPosX()+ int(GetWidth()*0.5f), (int)this->GetPosY() + int(GetHeight()*0.5f)  };
	return collision;
}

bool CBullet::CheckCollision (IEntity* pOther)
{
	if (pOther == owner)
		return false;
	if (CEntity::CheckCollision(pOther) == false)
		return false;
	switch (pOther->GetType())
	{
	default:
	case OBJ_BASE:
	case OBJ_BULLET:
		return false;
	case OBJ_ENEMY:
	case OBJ_FLYING_ENEMY:
	case OBJ_PLAYER:
	case OBJ_PLATFORM:
		{
			CDestoryBulletMessage* pMsg = new CDestoryBulletMessage(this);
			CMessageSystem::GetInstance()->SendMsg( pMsg );
			pMsg = nullptr;
		}
		break;
	}
	return true;
}

void CBullet::SetOwner(CEntity* ptr)
{
	if (owner != nullptr)
	{
		owner->Release();
	}
	owner = ptr;

	if (owner != nullptr)
	{
	owner->AddRef();
	}
}
